package com.supply.dl.app.http;

import android.content.Context;

import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * rxjava 中对observable上流对象的 的 转换,避免每次都去写
 * <p>
 * <pre>
 *    observable.subscribeOn(Schedulers.io())
 *              .observeOn(AndroidSchedulers.mainThread());
 * <pre/>
 *
 * Author: tian <br>
 * Time: 2018/5/18 10:43
 */
public class RxSchedulers {

    public static <T> ObservableTransformer<T, T> compose(final Context context) {
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> observable) {

                //对可能存在的泄露的处理
                if (context instanceof RxAppCompatActivity)
                    return observable
                            .compose(((RxAppCompatActivity) context).<T>bindUntilEvent(ActivityEvent.DESTROY))
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread());
                return
                        observable
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }


}
